<template>
  <div class=''>
    <el-form :model="spuForm" label-width="100px" size="small">
      <el-form-item label="SPU名称">
        <el-input placeholder="SPU名称" v-model="spuForm.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select v-model="spuForm.tmId">
          <el-option :value="item.id" :label="item.tmName" v-for="item in trademarkList"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input v-model="spuForm.description" placeholder="SPU名称" :rows="3" type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="SPU图片">
        <el-upload action="http://gmall-h5-api.atguigu.cn/admin/product/upload" list-type="picture-card"
          :on-preview="handlePictureCardPreview" :file-list="spuImgList" :on-remove="handleRemove"
          :on-success="handleAvatarSuccess">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select v-model="selectValue" style="margin-right: 10px;" :placeholder="`还有${saleAttrList.length}个未选择`">
          <el-option :value="`${item.id}-${item.name}`" :label="item.name" v-for="item in saleAttrList"></el-option>
        </el-select>
        <el-button type="primary" @click="addSaleAttr" :disabled="selectValue && !saleAttrList.length">添加销售属性</el-button>
      </el-form-item>
      <el-form-item>
        <el-table border :data="spuForm.spuSaleAttrList" style="width: 100%">
          <el-table-column type="index" align="center" label="序号" width="80">
          </el-table-column>
          <el-table-column prop="saleAttrName" label="属性名" width="200">
          </el-table-column>
          <el-table-column prop="name" label="属性值列表">
            <template slot-scope="{ row, $index }">
              <el-tag v-for="(saleAttrVal, index) in row.spuSaleAttrValueList" :key="index" style="margin-right: 5px;"
                closable :disable-transitions="false" @close="handleClose(index, row.spuSaleAttrValueList)">
                {{ saleAttrVal.saleAttrValueName }}
              </el-tag>
              <el-input v-if="row.inputVisible" v-model="row.inputValue" ref="InputRef" @blur="handleInputConfirm(row)"
                @keyup.enter="handleInputConfirm(row)" size="small" style="width: 100px;" />
              <el-button v-else size="small" @click="showInput(row)">新增</el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80px">
            <template slot-scope="{row,$index}">
              <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteSaleAttr($index)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button @click="saveSpuForm" type="primary">保存</el-button>
        <el-button @click="cancelHandler">取消</el-button>
      </el-form-item>
    </el-form>

  </div>
</template>

<script>
import { mapState } from "vuex";
import spuApi from '@/api/spu'
import { cloneDeep } from 'lodash'
export default {
  name: 'SpuForm',
  data() {
    return {
      selectValue: '',
      dialogImageUrl: '',
      dialogVisible: false,
      spuImgList: [],
      spuForm: this.initSpuForm(),
      trademarkList: [],
      baseSaleAttrList: []
    }
  },
  props: ['spuInfo'],
  methods: {
    // 点击取消的回调
    cancelHandler() {
      this.$emit('spuInfo')
      this.$emit('changeStatus', 1)
    },
    // 修改spu的功能函数
    async updateSpuInfo() {
      try {
        await spuApi.updateSpuInfo(this.spuForm)
        this.$message.success('修改销售属性成功')
      } catch (error) {
        console.error(error)
        this.$message.error('修改销售属性失败，请重试')
      }
    },
    // 点击编辑按钮获取图片数据
    async getSpuImageListBySpuId() {
      try {
        let result = await spuApi.getSpuImageListBySpuId(this.spuForm.id)
        this.spuImgList = result.data.map(item => {
          return {
            ...item,
            name: item.imgName,
            url: item.imgUrl
          }
        })
      } catch (error) {
        this.$message.error('获取图片数据失败，请重试')
        console.error(error)
      }
    },
    // 点击编辑获取销售属性数据
    async getSpuSaleAttrListBySpuId() {
      try {
        let result = await spuApi.getSpuSaleAttrListBySpuId(this.spuForm.id)
        this.spuForm.spuSaleAttrList = result.data
      } catch (error) {
        this.$message.error('获取销售属性数据失败，请重试')
        console.error(error)
      }
    },
    // 初始化spuForm的回调
    initSpuForm() {
      return {
        spuName: '',
        tmId: '',
        description: '',
        spuImageList: this.spuImgList,
        spuSaleAttrList: [],
        category3Id: '',
        id: ''
      }
    },
    // 保存spu的功能函数
    async saveSpuInfo() {
      try {
        await spuApi.saveSpuInfo(this.spuForm)
        this.$message.success('保存销售属性成功')
      } catch (error) {
        this.$message.error('保存销售属性失败，请重试')
        console.error(error)
      }
    },
    // 点击保存的回调
    saveSpuForm() {
      this.spuForm.category3Id = this.category3Id
      let tmpSpuImgList = this.spuImgList
      this.spuForm.spuImageList = tmpSpuImgList.map(item => {
        return {
          imgName: item.name,
          imgUrl: item.id ? item.imgUrl : item.response.data
        }
      })
      this.spuForm.spuSaleAttrList.forEach(item => {
        delete item.inputValue
        delete item.inputVisible
      })
      // 非空校验
      const { spuName, description, category3Id, tmId, spuSaleAttrList, spuImageList: spuImageList2 } = this.spuForm;
      if (!(spuName && description && category3Id && tmId && spuSaleAttrList.length && spuImageList2.length)) {
        this.$message.error('spu数据不完整，请填写完整!')
        return
      }
      if (this.spuForm.id) {
        this.updateSpuInfo();
      } else {
        this.saveSpuInfo();
      }
      this.cancelHandler()
    },
    // 输入框失焦事件的回调
    handleInputConfirm(row) {
      row.inputVisible = false
      // 非空校验
      if (!row.inputValue?.trim()) {
        return
      }
      // 去重校验
      let isRepeat = row.spuSaleAttrValueList.some(item => item.saleAttrValueName == row.inputValue)
      if (isRepeat) {
        this.$message.error("已存在该属性值，请重新输入")
        row.inputValue = ''
        return
      }
      row.spuSaleAttrValueList.push({
        baseSaleAttrId: row.baseSaleAttrId,
        saleAttrValueName: row.inputValue.trim()
      })
      row.inputValue = ''
    },
    // 点击新增属性值的回调
    showInput(row) {
      row.inputVisible = true
      this.$nextTick(() => {
        this.$refs.InputRef.focus()
      })
    },
    // 删除销售属性
    deleteSaleAttr(index) {
      this.spuForm.spuSaleAttrList.splice(index, 1)
    },
    // 点击添加销售属性的回调
    addSaleAttr() {
      const [baseSaleAttrId, saleAttrName] = this.selectValue.split('-')
      this.spuForm.spuSaleAttrList.push({
        baseSaleAttrId: baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: [],
        inputVisible: false,
        inputValue: ''
      })
      // 清空销售属性下拉框内容
      this.selectValue = '';
    },
    // 获取销售属性的功能函数
    async getBaseSaleAttrList() {
      try {
        let result = await spuApi.getBaseSaleAttrList()
        this.baseSaleAttrList = result.data
      } catch (error) {
        console.error(error)
      }
    },
    // 获取品牌的功能函数
    async getTrademarkList() {
      try {
        let result = await spuApi.getTrademarkList()
        this.trademarkList = result.data
      } catch (error) {
        console.error(error)
      }
    },
    // 图片上传成功的回调
    handleAvatarSuccess(res, file, fileList) {
      this.spuImgList = fileList
    },
    // 删除图片的回调
    handleRemove(file, fileList) {
      this.spuImgList = fileList
    },
    // 图片预览的回调
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    }
  },
  mounted() {
    if (this.spuInfo.id) {
      this.spuForm = cloneDeep(this.spuInfo)
      this.getSpuSaleAttrListBySpuId()
      this.getSpuImageListBySpuId();
    }
    this.getTrademarkList()
    this.getBaseSaleAttrList()
  },
  computed: {
    ...mapState('category', ['category3Id']),
    saleAttrList() {
      return this.baseSaleAttrList.filter(item => {
        let isHad = this.spuForm.spuSaleAttrList?.some(saleAttr => saleAttr.baseSaleAttrId == item.id)
        return !isHad
      })
    }
  }
}
</script>

<style></style>